package com.dwsoft.word;

import com.dwsoft.pojo.DataKpiDO;
import com.dwsoft.utils.Regexs;
import com.dwsoft.xml.XTable;
import org.springframework.stereotype.Component;
import word.w2004.Document2004;
import word.w2004.elements.tableElements.TableEle;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author sqw
 * @version 1.0
 * @description TODO
 * @ClassName WTable
 * @Date 2020/8/14
 * @since jdk1.8
 */
@Component("table")
public class WTable extends WElement<XTable> {

    @Override
    public void instance(XTable table, Document2004 document) throws Exception{
        String headKpi = table.getHeadKpi();
        String field=table.getField();
        String name=table.getName();
        String bodyKpi=table.getDataKpi();
        word.w2004.elements.Table tbl=new word.w2004.elements.Table();
        List<Map<String,String>> heads=kpiInstance(headKpi);
        List<String> headNams=new ArrayList<>();
        for(Map<String,String> head : heads){
            headNams.add(head.get(name));
        }
        tbl.addTableEle(TableEle.TH,headNams.toArray(new String[headNams.size()]));
        for(Map<String,String> val : kpiInstance(bodyKpi)){
            List<String> values=new ArrayList<>();
            for(Map<String,String> head : heads){
                String fid=head.get(field).toUpperCase();
                Object v=val.get(fid);
                values.add(String.valueOf(v));
            }
            tbl.addTableEle(TableEle.TD,values.toArray(new String[values.size()]));
        }
        document.addEle(tbl);
    }

    private List<Map<String,String>> kpiInstance(String kpi){
        DataKpiDO kpiDO = dataKpiMapper.getKpi(kpi);
        String script=kpiDO.getKpiScript();
        if(params!=null){
            script= Regexs.whereSql(params,kpiDO.getKpiScript());
        }
        List<Map<String,String>> rs = dataKpiMapper.getKpiValueForList(script);
        return rs;
    }
}
